<?php

namespace App\V3\V3_2_7\Controllers;

use App\Models\TallyModel;
use App\V3\V3_2_7\Models\CheckModel;
use App\V3\V3_2_7\Models\SellGoodsDetailBatchModel;
use App\V3\V3_2_7\Models\SellGoodsDetailModel;
use App\V3\V3_2_7\Models\SellModel;
use App\V3\V3_2_7\Models\SellPackageBatchModel;
use App\V3\V3_2_7\Models\SellPackageDetailModel;
use App\V3\V3_2_7\Models\SellPayRecordModel;
use App\V3\V3_2_7\Services\OutAnimalTagService;
use App\V3\V3_2_7\Services\OutInRepealService;
use App\V3\V3_2_7\Services\SellService;
use App\Helper\Utils\TimeUtil;
use App\Rules\JsonArray;
use App\Services\IncomeExpensesService;
use App\V3\V3_2_7\Models\SellDriverModel;
use App\V3\V3_2_7\Models\SellOtherChargesModel;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\V3\V3_2_7\Services\SalesReturnService;
use App\Services\CommonService;
use Illuminate\Support\Carbon;
use App\V3\V3_2_7\Models\SellLogisticsInfoModel;

class SellController extends BaseController
{
    //销售序列号列表
    public function sellSerialNumber(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'materiel_type_id' => 'required',//页面大小

            'pageSize' => 'required|integer',//页面大小
            'currentPage' => 'required|integer',//当前页
        ], [
            'materiel_type_id.required' => '参数`商品id`缺失',
            'pageSize.required' => '参数`pageSize`缺失',
            'pageSize.integer' => '参数`pageSize`仅能为数字',
            'currentPage.required' => '参数`currentPage`缺失',
            'currentPage.integer' => '参数`currentPage`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        return $this->success(SalesReturnService::salesReturnSerialNumber($request->materiel_type_id, $status = 1, $data));
    }

    /**
     * 添加销售单
     * change 在 2021/11/1 16:46 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'customer_name' => 'required',//客户姓名
            /*  'discount' =>'integer|min:0',//折扣 ：百分比
             'tax_rate' =>'integer|min:0',//税率 ：百分比 */
            'is_zero_suppression' => [
                'required',
                Rule::In([0, 1]),
            ],//是否抹零：0-否 1-是
            'final_money' => 'min:0',//实际应收金额（即折扣或抹零后价格）
            'deliver_goods_type' => [
                Rule::In([1, 2, 3])
            ],//发货方式：1-自提 2-代发 3-送货
            'transport_type' => [
                Rule::In([1, 2, 3, 4])
            ],//运输方式：1-空运 2-海运 3-铁路 4-公路
            'is_auto_out_storage' => [
                'required',
                Rule::In([0, 1]),
            ],//是否自动出库：0-否 1-是
            'consignee' => 'string',//收货人
            //'approver' =>'required|integer',//审批人
            'phone' => 'string',//联系电话
            'address' => 'string',//地址
            'remark' => 'string',//备注
            'out_order_no' => 'string',//外部单号
            'sell_date' => 'required|date',//销售时间
            'proof_image' => 'string',//凭证图片(多图逗号分隔)
            'real_money' => 'string',//实收金额（实际入账）
            'is_draft' => [
                'required',
                Rule::In([0, 1])
            ],//是否草稿：1-是 0-否
            'source' => [
                Rule::In([0, 1, 2, 3, 4, 5, 6])
            ]//订单来源:0-未知 1-安卓 2-ios 3-pc 4-微信小程序 5-抖音小程序
        ], [
            'customer_name.required' => '请填写客户姓名',
            //'approver.required' => '请选择审批人',
            'approver.integer' => '审批人`ID`为整数',
            'is_auto_out_storage.required' => '自动出库，参数缺失！',
            'is_auto_out_storage.in' => '自动出库参数值有误！',
            'goods_info.required' => '请填写商品信息',
            /*    'discount.integer' => '折扣仅能为数字',
               'discount.min' => '折扣最小只能为0',
               'tax_rate.integer' => '税率仅能为数字',
               'tax_rate.min' => '税率最小只能为0', */
            'is_zero_suppression.required' => '请选择是否抹零',
            'is_zero_suppression.in' => '您选择了未知的抹零方式',
            /* 'final_money.integer' => '实际应收金额仅能为数字', */
            'final_money.min' => '实际应收金额最小只能为0',
            'deliver_goods_type.in' => '您选择了未知的发货方式',
            'transport_type.in' => '您选择了未知的运输方式',
            'sell_date.required' => '请选择销售时间',
            'sell_date.date' => '销售时间不符合要求，请重新选择',
            'is_draft.required' => '请选择是否设置为草稿',
            'is_draft.in' => '选择了错误的草稿方式',
            'source.in' => '未知的订单来源'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        //报溢报损主单
        $mainInfo = $data;
        unset($mainInfo['batch_id']);
        unset($mainInfo['goods_info']);
        unset($mainInfo['package_info']);
        unset($mainInfo['sell_logistics_info']);
        $mainInfo['main_id'] = $this->getMainUserId();
        $mainInfo['user_id'] = $this->getUserId();
        $mainInfo['created_at'] = time();
        $mainInfo['sell_date'] = strtotime($data['sell_date']);
        $mainInfo['sell_time'] = strtotime(date('Y-m-d', strtotime($data['sell_date'])));
        $mainInfo['order_no'] = CommonService::getOrderNo(new SellModel, 'order_no', 'S');//订单号
        $data['batch_title'] = $this->batchTitle();
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        $isUseShelf = $this->isUseShelf();
        $isShareShelfLocation = $this->isShareShelfLocation();
        return Cache::lock(__CLASS__ . __FUNCTION__ . $data['user_id'], 5)
            ->get(function () use ($data, $mainInfo,$isUseShelf, $isShareShelfLocation) {
                $result = SellService::add($mainInfo, $data, $isUseShelf, $isShareShelfLocation);
                return response()->json($result);
            });
    }

    /**
     * 销售单列表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/25 16:20
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer|min:1',//当前页
            'repeal_status' => [
                'required',
                Rule::In([0, 1])
            ],//撤销状态：0-未撤销 1-已撤销
            'search_type' => [
                'required',
                Rule::In([1, 2, 3, 4, 5, 6, 7, 8])
            ],
            'status' => [
                'required',
                Rule::In([0, 1, 2, 3, 4, 5, 6])
            ]
        ], [
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`仅能为数字',
            'pageSize.min' => '`页面大小`仅能为1',
            'currentPage.required' => '`当前页大小`缺失',
            'currentPage.integer' => '`当前页`仅能为数字',
            'currentPage.min' => '`当前页`仅能为1',
            'repeal_status.required' => '`撤销状态`缺失',
            'repeal_status.in' => '`撤销状态`不合法',
            'search_type.required' => '`搜索类型`缺失',
            'search_type.in' => '`搜索类型`不合法',
            'status.required' => '`状态`缺失',
            'status.in' => '`状态`不合法',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if ($this->getUserId() == $this->getMainUserId()) {
            $userId['a.main_id'] = ['EQ' => $this->getMainUserId()];
        } else {
            if ($this->isShareSell()) {
                $userId['a.main_id'] = ['EQ' => $this->getMainUserId()];
            } else {
                $userId['a.user_id'] = ['EQ' => $this->getUserId()];
            }
        }
        $data['user_id'] = $this->getMainUserId();
        $data['main_id'] = $this->getUserId();
        $info = SellService::list($userId, $data);

        return $this->success($info);
    }
    /**
     * 销售单列表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/25 16:20
     * @return \Illuminate\Http\JsonResponse
     */
    public function newIndex(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer|min:1',//当前页
            'repeal_status' => [
                'required',
                Rule::In([0, 1])
            ],//撤销状态：0-未撤销 1-已撤销
            'search_type' => [
                'required',
                Rule::In([1, 2, 3, 4, 5, 6, 7, 8])
            ],
            'status' => [
                'required',
                Rule::In([0, 1, 2, 3, 4, 5, 6])
            ]
        ], [
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`仅能为数字',
            'pageSize.min' => '`页面大小`仅能为1',
            'currentPage.required' => '`当前页大小`缺失',
            'currentPage.integer' => '`当前页`仅能为数字',
            'currentPage.min' => '`当前页`仅能为1',
            'repeal_status.required' => '`撤销状态`缺失',
            'repeal_status.in' => '`撤销状态`不合法',
            'search_type.required' => '`搜索类型`缺失',
            'search_type.in' => '`搜索类型`不合法',
            'status.required' => '`状态`缺失',
            'status.in' => '`状态`不合法',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if ($this->getUserId() == $this->getMainUserId()) {
            $userId['a.main_id'] = ['EQ' => $this->getMainUserId()];
        } else {
            if ($this->isShareSell()) {
                $userId['a.main_id'] = ['EQ' => $this->getMainUserId()];
            } else {
                $userId['a.user_id'] = ['EQ' => $this->getUserId()];
            }
        }
        $data['user_id'] = $this->getMainUserId();
        $data['main_id'] = $this->getUserId();
        $info = SellService::newList($userId, $data);

        return $this->success($info);
    }
    /**
     * 销售单详细
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/25 17:04
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail(Request $request)
    {

        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required',//销售单主键id
        ], [
            'id.required' => '参数`销售单id`缺失'
        ]);

        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        return response()->json(SellService::detail($request->id));
    }

    /**
     * 销售单详细
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function newSellDetail(Request $request)
    {

        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required',//销售单主键id
        ], [
            'id.required' => '参数`销售单id`缺失'
        ]);

        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        return response()->json(SellService::newSellDetail($request->id));
    }

    /**
     * 最后的销售单详细
     * @param Request $request
     * AUTHOR  : zlf
     * DateTime: 2023/5/25 17:04
     * @return \Illuminate\Http\JsonResponse
     */
    public function lastSellDetail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'customer_id' => 'required',//销售单主键
        ], [
            'customer_id.required' => '参数`客户id	`缺失'
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $condition['main_id'] = $this->getMainUserId();
        $condition['customer_id'] = $data['customer_id'];
        $lastSellInfo = SellModel::select('id')->where($condition)
            ->where([
                'delete_flag' => 0
            ])->orderBy('created_at', 'DESC')->first();
        if (empty($lastSellInfo->id)) {
            return response()->json(['code' => 1, 'msg' => '没有销售订单信息', 'data' => '']);
        }
        return response()->json(SellService::detail($lastSellInfo->id));
    }

    /**
     * 删除
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/25 17:05
     * @return \Illuminate\Http\JsonResponse
     */
    public function del(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required',//销售单主键
        ], [
            'id.required' => '参数`销售单id`缺失'
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        SellModel::where('id', $data['id'])->update([
            'delete_flag' => 1
        ]);
        $orderNo = SellModel::where('id', $data['id'])->value('order_no');
        $logData = '销售单号：' . $orderNo . '已删除！';
        $this->log('删除销售单', $data, $logData);
        return $this->success();
    }

    /**
     * 编辑
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/26 14:51
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required|integer',//主键id
//            'customer_name' =>'required',//客户姓名
            /* 'discount' =>'integer|min:0',//折扣 ：百分比
            'tax_rate' =>'integer|min:0',//税率 ：百分比 */
            'is_zero_suppression' => [
                'required',
                Rule::In([0, 1]),
            ],//是否抹零：0-否 1-是
            'final_money' => 'min:0',//实际应收金额（即折扣或抹零后价格）
            'deliver_goods_type' => [
                Rule::In([1, 2, 3])
            ],//发货方式：1-自提 2-代发 3-送货
            'transport_type' => [
                Rule::In([1, 2, 3, 4])
            ],//运输方式：1-空运 2-海运 3-铁路 4-公路
            'consignee' => 'string',//收货人
            'phone' => 'string',//联系电话
            //'approver' =>'required',//审批人
            'address' => 'string',//地址
            'remark' => 'string',//备注
            'out_order_no' => 'string',//外部单号
            'sell_date' => 'required|date',//销售时间
            'proof_image' => 'string',//凭证图片(多图逗号分隔)
            'real_money' => 'string',//实收金额（实际入账）
            'is_draft' => [
                'required',
                Rule::In([0, 1])
            ],//是否草稿：1-是 0-否
            'source' => [
                Rule::In([0, 1, 2, 3, 4, 5])
            ]//订单来源:0-未知 1-安卓 2-ios 3-pc 4-微信小程序 5-抖音小程序
        ], [
            'id.required' => '参数`销售单id`缺失',
            /*'approver.required' => '请选择审批人',
            'approver.integer' => '审批人`ID`为整数',*/
            'goods_info.required' => '请填写商品信息',
            /*  'discount.integer' => '折扣仅能为数字',
             'discount.min' => '折扣最小只能为0',
             'tax_rate.integer' => '税率仅能为数字',
             'tax_rate.min' => '税率最小只能为0', */
            'is_zero_suppression.required' => '请选择是否抹零',
            'is_zero_suppression.in' => '您选择了未知的抹零方式',
            /* 'final_money.integer' => '实际应收金额仅能为数字', */
            'final_money.min' => '实际应收金额最小只能为0',
            'deliver_goods_type.in' => '您选择了未知的发货方式',
            'transport_type.in' => '您选择了未知的运输方式',
            'sell_date.required' => '请选择销售时间',
            'sell_date.date' => '销售时间不符合要求，请重新选择',
            'is_draft.required' => '请选择是否设置为草稿',
            'is_draft.in' => '选择了错误的草稿方式',
            'source.in' => '未知的订单来源'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        //报溢报损主单
        $mainInfo = $data;
        if (isset($mainInfo['sell_date'])) $mainInfo['sell_date'] = strtotime($data['sell_date']);
        if (isset($mainInfo['order_time'])) $mainInfo['order_time'] = strtotime($data['order_time']);
        if (isset($mainInfo['deliver_time'])) $mainInfo['deliver_time'] = strtotime($data['deliver_time']);
        $mainInfo['main_id'] = $this->getMainUserId();
        $mainInfo['user_id'] = $this->getUserId();
        $data['batch_title'] = $this->batchTitle();

        $result = SellService::edit($mainInfo, $data, $this->isUseShelf(), $this->isShareShelfLocation());

        return response()->json($result);
    }

    /**
     * 收款
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/26 15:32
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMoney(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'sell_id' => 'required|integer',//销售单主键
            'money' => 'numeric|min:0',//收款金额
            'collection_time' => 'required|date',//收款时间
            //'collection_account'=>'required|string',//收款账号
            'status' => 'required|integer',//收款状态：1-全部 2-部分
        ], [
            'money.numeric' => '金额异常，只能为数字，请重新输入',
            'money.min' => '金额不能低于0'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        //开启事务
        DB::beginTransaction();
        try {
            $model = SellModel::query()->where('id', $data['sell_id'])->first();//销售单信息
            if (strtotime($model['created_at']) > '1713506400') {//2024年4月19日 14点之前的订单不需要审核
                $checkInfo = CheckModel::where([
                    'all_id' => $model['id'],
                    'type' => 2,
                    'repeal_status' => 0
                ])->first();
                if (!empty($checkInfo)) {
                    if (empty($checkInfo['eudit_status'])) {
                        throw new Exception('销售单在待审批中！');

                    }
                    if ($checkInfo['eudit_status'] == 2) {
                        throw new Exception('销售单未审批通过！');

                    }
                }
            }
            $model->flag = $data['flag'] ?? 0;
            $inMomey = SellPayRecordModel::where('sell_id', $data['sell_id'])->sum('expend');//已收款金额
            //全部收款
            if ($data['status'] == 1) {
                $model->pay_status = 2;
                $model->real_money = $model->final_money + $model->other_charges;
                $model->save();
                //支付完成更新商品支付状态
                SellGoodsDetailModel::where('sell_id', $data['sell_id'])->update(['pay_status' => 1]);
                //支付完成更新套餐支付状态
                SellPackageDetailModel::where('sell_id', $data['sell_id'])->update(['pay_status' => 1]);

                $money = ($model['final_money'] + $model['other_charges']) - $inMomey;
            } else {//部分收款
                //收款超额检测
                if (($inMomey + $data['money']) > ($model['final_money'] + $model['other_charges'])) {
                    return $this->fail('', '超出剩余应付金额');
                }
                if (($inMomey + $data['money']) < ($model['final_money'] + $model['other_charges'])) {
                    $model->real_money = $inMomey + $data['money'];
                    $model->pay_status = 1;
                }
                if (($inMomey + $data['money']) == ($model['final_money'] + $model['other_charges'])) {
                    $model->pay_status = 2;
                    $model->real_money = $model->final_money + $model->other_charges;
                    //支付完成更新商品支付状态
                    SellGoodsDetailModel::where('sell_id', $data['sell_id'])->update(['pay_status' => 1]);
                    //支付完成更新套餐支付状态
                    SellPackageDetailModel::where('sell_id', $data['sell_id'])->update(['pay_status' => 1]);
                }

                $model->save();
                $money = $data['money'];
            }

            //收款记录
            $data['collection_time'] = strtotime($data['collection_time']);
            $data['created_at'] = time();
            $data['main_id'] = $this->getMainUserId();
            unset($data['status']);
            unset($data['money']);
            $data['expend'] = $money;
            $data['pay_type'] = !empty($data['pay_type']) ? $data['pay_type'] : 0;
            SellPayRecordModel::insert($data);
            $logData = '销售单号：' . $model['order_no'] . '收款金额为：' . $money . '元';
            $this->log('销售单收款', $data, $logData);

            IncomeExpensesService::tally(0, $model, $money, $this->getMainUserId(), $model['sell_date'], $this->getUserId());
            DB::commit();//提交事务
            return $this->success();
        } catch (Exception $e) {
            DB::rollBack();//事务回滚
            Log::debug('销售单收款' . var_export($e->getMessage(), true));
            //异常响应
            return $this->fail('', $e->getMessage());
        }
    }

    /**
     * 重新下单
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/26 15:33
     * @return \Illuminate\Http\JsonResponse
     */
    public function addAgain(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required|integer',//销售单主键
        ], [
            'id.required' => '参数`销售单id`缺失'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        $data['batch_title'] = $this->batchTitle();

        return response()->json(SellService::addAgain($data));
    }

    public function out(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required|integer',//销售单主键id
            'status' => 'required|integer',//出入库状态：0-部分 1-全部
            'in_storage_time' => 'nullable|date_format:Y-m-d H:i:s',//出库时间
            'remark' => 'string',//备注
        ], [
            'id.required' => '参数`销售单id`缺失',
            'status.required' => '参数`出库状态`缺失',
            'in_storage_time.date_format' => '出库时间格式错误',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['out_way'] = $this->getOutWay();
        $data['batch_title'] = $this->batchTitle();
        $data['is_use_shelf'] = $this->isUseShelf();
        $data['is_use_packages_components'] = $this->isUsePackagesComponents();
        //序列号
        $result = SellService::sellOut(
            1,
            $data['id'],
            $data['status'],
            empty($data['goods_info']) ? '' : $data['goods_info'],
            empty($data['package_info']) ? '' : $data['package_info'],
            $data,
            $this->isUseShelf()
        );
        $this->log('销售单出库', $data);
        return response()->json($result);
    }

    public function prepare(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required|integer',//销售单主键
        ], [
            'id.required' => '销售单id缺失'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['logTime'] = time();
        $this->operateLog('销售单预出库', $data, $data['logTime']);

        return response()->json(
            SellService::prepare($data)
        );
    }

    public function repeal(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required|integer',//销售单主键
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['out_way'] = $this->getOutWay();
        $res = OutInRepealService::repeal($data['id'], 1);
        if ($res == 0) {
            return $this->fail('', '商品被删除，无法撤销');
        } else if (isset($res['code']) && isset($res['code']) == 1) {
            return $this->success();
            //return $this->fail('', $res['msg']);
        }

        if ($res == 1) {
            $orderNo = SellModel::where('id', $data['id'])->value('order_no');
            $logData = '销售单号：' . $orderNo . '已撤销！';
            $this->log('撤销销售单', $data, $logData);
            return $this->success();
        }
    }

    public function payHistory(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//销售单主键
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return $this->success($res = SellService::payHistory($request->id) ?? []);
    }


    /**
     * 销售单设置批次号
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/24 17:23
     * @return \Illuminate\Http\JsonResponse
     */
    public function sellAddBatch(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'info' => [
                'required',
                'json',
                new JsonArray([
                    'batch_id' => 'required|numeric',//批次id
                    'storage_manage_id' => 'required|numeric|',//库存id
                    'num' => 'required|numeric' //要使用的批次数量
                ])
            ],
            'id' => 'required|numeric',//销售单内商品或销售单内套餐商品id
            'sell_id' => 'required|numeric|', //销售单id
            'type' => [
                'required',
                Rule::In([0, 1]),
            ],//条码类型0:商品;1:套餐;
        ], [
            'id.required' => '参数`销售单内商品或销售单内套餐商品id`缺失',
            'sell_id.required' => '参数`sell_id`缺失',
            'sell_id.numeric' => '参数`sell_id`类型错误',
            'type.required' => '参数`type`缺失',
            'type.In' => '参数`type`不合法',
            'info.required' => '参数`info`缺失',
            'info.json' => '参数`info`仅能为json',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();

        $this->log('设置批次号', $data, '设置成功！');
        return response()->json(
            SellService::sellAddBatch($data)
        );
    }

    public function sellBatchList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//销售单id
            'type' => [
                'required',
                Rule::In([0, 1]),
            ],//条码类型0:商品;1:套餐;
            'materiel_type_id' => 'required|integer',//销售单id
        ], [
            'id.required' => '参数`sell_id`缺失',
            'id.integer' => '参数`sell_id`异常',
            'materiel_type_id.required' => '参数`商品id`类型错误',
            'materiel_type_id.integer' => '参数`商品id`异常',
            'type.required' => '参数`type`缺失',
            'type.In' => '参数`type`不合法',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return $this->success(
            SellService::sellBatchList($data)
        );
    }

    /**
     * 编辑销售单内商品批次信息
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/7/2 16:59
     * @return \Illuminate\Http\JsonResponse
     */
    public function sellBatchEdit(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
//            'id'=>'required|integer',//销售单id
            'goods_batch_id' => 'required|integer',//销售单内商品或销售单内套餐商品批次id
            'type' => [
                'required',
                Rule::In([0, 1]),
            ],//条码类型0:商品;1:套餐;
            'num' => 'required|min:0'
        ], [
            'goods_batch_id.required' => '参数`销售单内商品批次id`缺失',
            'goods_batch_id.integer' => '参数`销售单内商品批次id`异常',
            'type.required' => '参数`type`缺失',
            'type.In' => '参数`type`不合法',
            'num.required' => '参数`数量`缺失',
            'num.min' => '参数`数量`最小只能为0',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $this->log('编辑商品批次信息', $data, '编辑成功！');
        return response()->json(
            SellService::sellBatchEdit($data)
        );
    }

    public function sellBatchDel(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'goods_batch_id' => 'required|integer',//销售单内商品或销售单内套餐商品批次id
            'type' => [
                'required',
                Rule::In([0, 1]),
            ],//条码类型0:商品;1:套餐;
        ], [
            'goods_batch_id.required' => '参数`销售单内商品批次id`缺失',
            'goods_batch_id.integer' => '参数`销售单内商品批次id`异常',
            'type.required' => '参数`type`缺失',
            'type.In' => '参数`type`不合法',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        if ($data['type'] == 0) {
            $sellGoodsDetailBatchInfo = SellGoodsDetailBatchModel::where('id', $data['goods_batch_id'])
                ->first();

            if (empty($sellGoodsDetailBatchInfo)) {
                return $this->fail('', '目标商品批次不存在，无法操作');
            }

            if ($sellGoodsDetailBatchInfo['num'] != $sellGoodsDetailBatchInfo['rest_num']) {
                return $this->fail('', '目标商品批次已出库，无法删除');
            }

            SellGoodsDetailBatchModel::where('id', $data['goods_batch_id'])->delete();
        } else {
            $sellPackageBatchInfo = SellPackageBatchModel::where('id', $data['goods_batch_id'])->first();

            if (empty($sellPackageBatchInfo)) {
                return $this->fail('', '目标商品批次不存在，无法操作');
            }

            if ($sellPackageBatchInfo['num'] != $sellPackageBatchInfo['rest_num']) {
                return $this->fail('', '目标商品批次已出库，无法删除');
            }

            SellPackageBatchModel::where('id', $data['goods_batch_id'])->delete();
        }

        $this->log('删除销售单内商品或销售单内套餐商品批次信息', $data, '删除成功！');
        return $this->success();
    }

    /**
     * 销售单已有快递单号列表
     * @param Request $request
     * 2022/8/22 20:20
     * Author: Sun Wu
     * @return \Illuminate\Http\JsonResponse
     */
    public function sellExpressInfo(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer|min:1',//当前页
        ], [
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`仅能为数字',
            'pageSize.min' => '`页面大小`仅能为1',
            'currentPage.required' => '`当前页大小`缺失',
            'currentPage.integer' => '`当前页`仅能为数字',
            'currentPage.min' => '`当前页`仅能为1',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        //是否共享
        $condition = [];
        if (!$this->isShareExpress()) {
            if ($this->getUserTpye()) {
                $condition['user_id'] = ['EQ' => $this->getUserId()];
            } else {
                $condition['main_id'] = ['EQ' => $this->getMainUserId()];
            }
        } else {
            $condition['main_id'] = ['EQ' => $this->getMainUserId()];
        }

        $keyword = isset($data['code']) ? $data['code'] : '';

        $model = SellModel::select('logistics_order_no', 'logistics_company')->where($condition)
            ->where('repeal_status', 0)
            ->where('delete_flag', 0)
            ->where('logistics_order_no', '!=', '')
            ->where('logistics_order_no', 'LIKE', '%' . $keyword . '%')
            ->orderBy('id', 'desc')
            ->paginate($data['pageSize'], ['*'], '', $data['currentPage'])->toArray();

        return $this->success($model);
    }

    /**
     * 其他费用添加
     * change 在 2021/11/2 14:41 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function otherCharges(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'sell_id' => 'required|integer',//销售单主键id
            'money' => 'required|string',//其他费用
            'other_type_name' => 'required|string',//其他费用类型名称
            'other_remark' => 'string',//备注
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['main_id'] = $this->getMainUserId();
        $data['created_at'] = time();
        //开启事务
        DB::beginTransaction();
        try {
            SellOtherChargesModel::insert($data);
            $model = SellModel::where('id', $data['sell_id'])->first();
            $model->other_charges = $model->other_charges + $data['money'];
            $model->save();
            $this->log('销售单-添加其他费用', $data, '销售单号:' . $model['order_no'] . '添加其他费用为' . $data['money'] . '元');
            DB::commit();//提交事务
            return $this->success();
        } catch (Exception $e) {
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(), '添加其他费用');
        }
    }

    /**
     * 其他费用列表
     * change 在 2021/11/2 14:41 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function otherChargesList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'sell_id' => 'required|integer',//销售单主键id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $model = SellOtherChargesModel::where('sell_id', $data['sell_id'])->get();
        return $this->success($model);
    }

    /**
     * 其他费用编辑
     * change 在 2021/11/2 14:41 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function otherChargesEdit(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required|integer',//其他费用主键id
            'money' => 'required|string',//其他费用
            'other_type_name' => 'string',//其他费用类型名称
            'other_remark' => 'string',//备注
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        //开启事务
        DB::beginTransaction();
        try {
            $beforeModel = SellOtherChargesModel::where('id', $data['id'])->first();
            SellOtherChargesModel::where('id', $data['id'])->update($data);
            $beforeMoney = $beforeModel['money'];
            $final = $data['money'] - $beforeMoney;
            $model = SellModel::where('id', $beforeModel['sell_id'])->first();
            $model->other_charges = $model->other_charges + $final;
            $model->save();
            $this->log('销售单-编辑其他费用', $data, '销售单号:' . $model['order_no'] . '修改其他费用为' . $data['money'] . '元');
            DB::commit();//提交事务
            return $this->success();
        } catch (Exception $e) {
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(), '添加其他费用');
        }
    }

    /**
     * 绑定司机(添加编辑)
     * change 在 2021/11/2 09:40 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bindDriver(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'sell_id' => 'required|integer',//销售单主键id
            'plate_number' => 'required|string',//车牌
            'name' => 'required|string',//司机姓名
            'phone' => 'required|string',//提货司机电话
            'logistics_company' => 'string',//物流公司
            'remark' => 'string',//备注
            'plate_image' => 'string',//车牌照片
            'id_card_image' => 'string',//身份证照片
            'driving_licence' => 'string',//驾驶证照片
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['main_id'] = $this->getMainUserId();
        $data['created_at'] = time();
        $orderNo = SellModel::where('id', $data['sell_id'])->value('order_no') ?? '';
        $res = '销售单：' . $orderNo . ' 司机名：' . $data['name'] . '添加成功';
        if (isset($data['driver_id'])) {
            $driverId = $data['driver_id'];
            unset($data['driver_id']);
            SellDriverModel::where('id', $driverId)->update($data);
            $res = '销售单号：' . $orderNo . '司机名：' . $data['name'] . '更改成功';
        } else {
            SellDriverModel::insert($data);
        }

        $this->log('编辑绑定司机', $data, $res);
        return $this->success();
    }

    public function sellSerialList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'type_id' => 'required|integer',//其他费用主键id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['main_id'] = $this->getMainUserId();

        return $this->success(
            sellService::sellSerialList($data)
        );
    }

    /**
     * 销售单添加物流信息
     * @param Request $request
     */
    public function addSellExpressNumber(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'sell_id' => 'required|integer',//销售单主键id
            'sell_logistics_info' => [
                'required',
                'json',
                new JsonArray([
                    'logistics_company' => 'required',//物流公司名称
                    'logistics_order_no' => 'required',//物流单号
                ])
            ]
        ], [
            'sell_id.required' => '销售单主键id,不能为空',
            'sell_id.integer' => '销售单主键id,只能为整数',
            'sell_logistics_info.required' => '物流信息,不能为空',
            'sell_logistics_info.json' => '物流信息数据格式为json',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['main_id'] = $this->getMainUserId();
        $orderNo = SellModel::where([
            'id' => $data['sell_id'],
            'main_id' => $this->getMainUserId()
        ])->value('order_no');
        if (!empty($orderNo)) {
            if (!empty($data['sell_logistics_info'])) {//添加物流信息
                $logisticsData = [];
                $sellLogisticsInfo = json_decode($data['sell_logistics_info'], true);
                if (is_array($sellLogisticsInfo)) {
                    foreach ($sellLogisticsInfo as $sVal) {
                        if (!empty($sVal['logistics_company']) && empty($sVal['logistics_order_no'])) {
                            return fail('', '物流公司名称：' . $sVal['logistics_company'] . '，物流号不能为空');
                        }
                        if (empty($sVal['logistics_company']) && !empty($sVal['logistics_order_no'])) {
                            return fail('', '物流号：' . $sVal['logistics_order_no'] . '，物流公司名称不能为空');
                        }
                        $logisticsData[] = [
                            'user_id' => $this->getUserId(),
                            'main_id' => $this->getMainUserId(),
                            'sell_id' => $data['sell_id'],
                            'logistics_company' => $sVal['logistics_company'],
                            'logistics_order_no' => $sVal['logistics_order_no'],
                            'created_at' => Carbon::now()->timestamp
                        ];
                    }
                    if (!empty($logisticsData)) {
                        SellLogisticsInfoModel::insert($logisticsData);
                    }
                } else {
                    return fail('', '物流信息异常');
                }
            }
        } else {
            return fail('', '销售单信息，没有找到！');
        }
        $logData = '销售单号 ：' . $orderNo . '的物流信息，添加成功！';
        $this->log('销售单添加物流信息', $data, $logData);
        return $this->success();
    }

    /**
     *销售司机列表
     * Author: zlf
     * Created at 2024/1/31 10:50
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sellDriverList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'sell_id' => 'required|integer',//销售单主键id
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer|min:1',//当前页
        ], [
            'sell_id.required' => '销售单主键id,不能为空',
            'sell_id.integer' => '销售单主键id,只能为整数',
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`仅能为数字',
            'pageSize.min' => '`页面大小`仅能为1',
            'currentPage.required' => '`当前页大小`缺失',
            'currentPage.integer' => '`当前页`仅能为数字',
            'currentPage.min' => '`当前页`仅能为1',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        $data['main_id'] = $this->getMainUserId();
        return $this->success(SellService::sellDriverList($data));
    }

    /**
     *删除销售司机
     * Author: zlf
     * Created at 2024/1/31 11:04
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delSellDriver(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'sell_id' => 'required|integer',//销售单主键id
            'driver_id' => 'required|integer',//司机表主键id
        ], [
            'sell_id.required' => '销售单主键id,不能为空',
            'sell_id.integer' => '销售单主键id,只能为整数',
            'driver_id.required' => '司机表主键id,不能为空',
            'driver_id.integer' => '司机表主键id,只能为整数',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        $data['main_id'] = $this->getMainUserId();
        return $this->success(SellService::delSellDriver($data));
    }
}
